/**
 * Created by George on 2018/2/25.
 *
 */

import util from "../common/util"


// 将本控制器函数作为结果返回给router.js
var createDuesCtrl = function ($scope, $http, $state) {
    $scope.welcome_info = "会费管理";
    $scope.recharge = {
        userId: "",
        dues: 100,
        date: util.getNowFormatDate(),
        info: "会费充值",
        usersData: [],
        type: "1",
        typeData: [
            {id: "0", name: "支出"},
            {id: "1", name: "收入"}
        ]
    };
    $scope.pageInfo = {
        pageNo: 1,
        pageSize: 100
    };
    $scope.$emit('updateRoute', 'dues');

    function init() {
        initOrUpdateData();
    }

    function initOrUpdateData() {
        $scope.recharge = {
            userId: "",
            dues: 100,
            date: util.getNowFormatDate(),
            info: "会费充值",
            usersData: [],
            type: "1",
            typeData: [
                {id: "0", name: "支出"},
                {id: "1", name: "收入"}
            ]
        };

        $http.get("/basketballfire/rest/user/list", {params: $scope.pageInfo}).then(function (data, status) {
            console.log(data);
            var usersData = data.data.data;
            usersData.sort(function(a, b){return a.name.localeCompare(b.name)});
            initUsersData(usersData);
        });
    }

    function initUsersData(usersData) {
        $scope.recharge.usersData = [];
        for (var index = 0; index < usersData.length; index++) {
            var user0 = {
                "id": usersData[index].id,
                "name": usersData[index].name
            };
            $scope.recharge.usersData.push(user0);
        }
    }

    $scope.addRechargeClick = function () {
        // $scope.recharge.userId = $('#rechargeUsersSelect option:selected').val();
        if ($scope.recharge.type === "1" && $scope.recharge.dues < 0 || $scope.recharge.type === "0" && $scope.recharge.dues > 0) {
            $scope.recharge.dues = -$scope.recharge.dues;
        }
        var data = {
            "userId": $scope.recharge.userId,
            "dues": $scope.recharge.dues,
            "date": $scope.recharge.date,
            "info": $scope.recharge.info,
            "type": $scope.recharge.type
        };
        $http.post('/basketballfire/rest/dues', data).then(function () {
            console.log("success!");
            alert("创建成功！");
            $state.go("dues");
        }, function () {
            console.log("failed!");
            alert("创建失败！");
        });
    };

    init();
};

export default createDuesCtrl;